package com.xli.mybatis.interceptor;

import com.xli.mybatis.anno.EncryptField;
import com.xli.mybatis.support.Encrypt;
import com.xli.mybatis.support.EncryptFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;

import java.lang.reflect.Field;
import java.sql.PreparedStatement;

@Slf4j
@Intercepts({@Signature(type = ParameterHandler.class, method = "setParameters", args = {PreparedStatement.class})})
public class EncryptInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        ParameterHandler parameterHandler = (ParameterHandler) invocation.getTarget();
        Object param = parameterHandler.getParameterObject();
        if (param != null) {
            Field[] fields = param.getClass().getDeclaredFields();
            for (Field field : fields) {
                if (field.isAnnotationPresent(EncryptField.class)) {
                    field.setAccessible(true);
                    try {
                        Object value = field.get(param);
                        if (value instanceof CharSequence) {
                            //字符串类型
                            EncryptField annotation = field.getAnnotation(EncryptField.class);
                            if (annotation != null) {
                                Encrypt service = EncryptFactory.getEncryptionService(annotation.type());
                                field.set(param, service.encrypt(value.toString(), annotation.key()));
                            }
                        }
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException("字段加密失败", e);
                    }
                }
            }
        }
        return invocation.proceed();
    }
}
